/**
 * 发送表情
 *
 * 有两种：
 * - 微信自带表情（emoji)，选中后以纯文本形式插入到文本框中
 * - 图片表情（狭义上的 emotion），选中后直接执行发送
 */
import { SmileOutlined, CloseCircleFilled, PlusOutlined } from '@ant-design/icons'
import { Popover, message } from 'antd'
import { emojiMap, default as EmojiItem } from '@/desktop/components/Emoji'
import { useUpload } from '@/desktop/components/upload'
import { flexCol } from '@/desktop/styles'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { ChatRecordType } from '@/services/contact-chat'
import s from './index.module.less'

export default function SendEmotion(props: { insertText: (text: string) => void }) {
  const { insertText } = props
  const [visible, setVisible] = useState(false)
  const emojiChoosed = (txt: string) => {
    insertText(txt)
    setVisible(false)
  }
  const close = () => setVisible(false)

  return <div>
    <Popover
      content={<EmotionPanel emojiChoosed={emojiChoosed} close={close} />}
      overlayClassName={s.popover}
      open={visible}
      onOpenChange={setVisible}
    >
      <SmileOutlined />
    </Popover>
  </div>
}

const emojis = [...emojiMap.keys()]

export function EmotionPanel(props: { emojiChoosed: (text: string) => void; close: () => void }) {
  const { emojiChoosed, close } = props

  const [emotions] = useStreams(services.resources.emotions.list)
  const sendEmotion = (url: string) => {
    void services.chat.send(ChatRecordType.Emotion, { name: '动画表情', url })
    close()
  }
  const removeEmotion = async (e: React.MouseEvent<HTMLSpanElement>, id: number) => {
    e.stopPropagation()
    const resp = await services.resources.emotions.remove(id)
    if (resp.success) void message.success('表情删除成功')
    else void message.success(`表情删除失败：${resp.error}`)
  }

  const [uploading, upload] = useUpload()
  const inputRef = useRef<HTMLInputElement>(null)
  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0] ?? null
    e.target.value = ''
    if (file) {
      const res = await upload(file)
      if (res) void services.resources.emotions.add(res.url)
    }
  }

  return <div styleName="panel">
    <section styleName="emojis">
      {emojis.map(code => <div key={code} styleName="emoji" onClick={() => emojiChoosed(code)}>
        <EmojiItem code={code} />
      </div>)}
    </section>
    <section styleName="emotions">
      {emotions.map(emotion => <div
        key={emotion.id}
        styleName="emotion"
        onClick={() => sendEmotion(emotion.file)}
      >
        <img src={emotion.file} />
        <CloseCircleFilled styleName="remove" onClick={e => void removeEmotion(e, emotion.id)} />
      </div>)}

      <div css={s2.add} onClick={() => !uploading && inputRef.current?.click()}>
        <PlusOutlined />
        <div>添加</div>
        <input type="file" accept=".gif" ref={inputRef} onChange={handleFile} />
      </div>
    </section>
  </div>
}

const s2 = {
  add: css`
    ${flexCol};
    align-items: center;
    background-color: #fafafa;
    border-radius: 2px;
    color: #333;
    cursor: pointer;
    &:hover {
      background-color: #f5f5f5;
    }
    .anticon {
      font-size: 20px;
      margin-bottom: 1px;
    }
    div {
      font-size: 12px;
      transform: scale(0.9);
      transform-origin: bottom center;
    }
    input {
      display: none;
    }
  `,
}
